<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>热点采集与趋势分析</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>

    <!-- 配置Tailwind自定义主题 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        neutral: '#F5F7FA',
                        dark: '#1D2129',
                        'platform-weibo': '#E6162D',
                        'platform-wechat': '#07C160',
                        'platform-zhihu': '#0066FF',
                        'platform-douyin': '#FE2C55',
                        'platform-bilibili': '#FB7299'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }

            .card-shadow {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }

            .card-hover {
                transition: all 0.3s ease;
            }

            .card-hover:hover {
                transform: translateY(-4px);
                box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
            }

            .topic-item {
                transition: all 0.2s ease;
            }

            .topic-item:hover {
                background-color: rgba(22, 93, 255, 0.05);
            }
        }
    </style>
    <style>
        .nav-links-hot-topic .nav-button {
            display: inline-block;
            padding: 8px 15px;
            background: #f0f0f0; /* 浅灰色背景 */
            color: #333; /* 深色文字 */
            text-decoration: none;
            border-radius: 20px;
            font-size: 14px;
            transition: all 0.3s ease;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); /* 更微弱的阴影 */
        }

        .nav-links-hot-topic .nav-button:hover {
            transform: translateY(-1px);
            background: #e0e0e0; /* 鼠标悬停时颜色稍深 */
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>

<body class="font-inter bg-gray-50 text-dark min-h-screen">
<!-- 顶部导航 -->
<header class="bg-white shadow-sm sticky top-0 z-50 transition-all duration-300" id="mainHeader">
    <div class="container mx-auto px-4 py-4 flex justify-between items-center">
        <div class="flex items-center space-x-2">
            <i class="fa fa-line-chart text-primary text-2xl"></i>
            <h1 class="text-xl md:text-2xl font-bold text-dark">热点采集与分析</h1>
        </div>
        <div class="flex items-center space-x-4">
            <nav class="flex items-center space-x-4 nav-links-hot-topic">
                <a href="/" class="nav-button">🏠 首页</a>
                <a href="/editor" class="nav-button">📝 文章编辑与查看</a>
                <a href="/multi_generator" class="nav-button">🚀 基于主题的文章生成</a>
            </nav>
            <button id="refreshBtn"
                    class="flex items-center space-x-1 text-primary hover:text-primary/80 transition-colors">
                <i class="fa fa-refresh"></i>
                <span class="hidden sm:inline">刷新数据</span>
            </button>
            <button id="themeToggle" class="text-gray-500 hover:text-dark transition-colors">
                <i class="fa fa-moon-o"></i>
            </button>
        </div>
    </div>
</header>

<main class="container mx-auto px-4 py-8">
    <!-- 状态提示区 -->
    <div id="statusMessage" class="mb-6 p-4 rounded-lg hidden"></div>

    <!-- 数据概览区 -->
    <section class="mb-10">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-bold">热点平台分布</h2>
            <div class="text-sm text-gray-500" id="updateTime"></div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- 平台分布图表 -->
            <div class="bg-white rounded-xl p-5 card-shadow col-span-1">
                <h3 class="text-lg font-semibold mb-4">热点数量占比</h3>
                <div class="aspect-square max-w-xs mx-auto">
                    <canvas id="platformChart"></canvas>
                </div>
            </div>

            <!-- 平台数据卡片 -->
            <div class="col-span-1 lg:col-span-2 grid grid-cols-2 md:grid-cols-3 gap-4" id="platformCards">
                <!-- 平台卡片将通过JS动态生成 -->
            </div>
        </div>
    </section>

    <!-- 热点话题列表区 -->
    <section>
        <h2 class="text-xl font-bold mb-6">各平台热门话题榜单</h2>

        <div id="topicsContainer" class="space-y-8">
            <!-- 平台话题列表将通过JS动态生成 -->
            <div class="flex justify-center items-center py-16">
                <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
            </div>
        </div>
    </section>
</main>

<footer class="bg-white border-t mt-12 py-6">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
        <p>热点趋势分析平台 &copy; <span id="currentYear"></span></p>
    </div>
</footer>

<script>
    // 全局变量
    let chartInstance = null;
    let isDarkMode = false;

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', () => {
        // 设置当前年份
        document.getElementById('currentYear').textContent = new Date().getFullYear();

        // 更新时间显示
        updateTimeDisplay();

        // 加载并渲染数据
        fetchAndRenderData();

        // 绑定事件监听
        bindEventListeners();
    });

    // 绑定事件监听
    function bindEventListeners() {
        // 刷新按钮
        document.getElementById('refreshBtn').addEventListener('click', () => {
            fetchAndRenderData(true);
        });

        // 主题切换按钮
        document.getElementById('themeToggle').addEventListener('click', toggleTheme);

        // 滚动时改变头部样式
        window.addEventListener('scroll', () => {
            const header = document.getElementById('mainHeader');
            if (window.scrollY > 10) {
                header.classList.add('py-2');
                header.classList.remove('py-4');
            } else {
                header.classList.add('py-4');
                header.classList.remove('py-2');
            }
        });
    }

    // 获取后端数据
    async function fetchTrendsData() {
        try {
            const response = await fetch('/api/filtered-trends');
            const result = await response.json();

            if (result.success) {
                return {
                    "success": true,
                    "data": result.data
                };
            } else {
                return {
                    "success": false,
                    "error": result.error || '获取数据失败',
                    "data": {}
                };
            }
        } catch (error) {
            console.error('Error fetching trends data:', error);
            return {
                "success": false,
                "error": '网络错误，请检查连接后重试',
                "data": {}
            };
        }
    }

    // 获取并渲染数据
    async function fetchAndRenderData(forceRefresh = false) {
        showLoadingState();

        try {
            const response = await fetchTrendsData();

            if (response.success) {
                renderAllData(response.data);
                showSuccessMessage('数据加载成功');
            } else {
                showErrorMessage(response.error || '获取数据失败');
            }
        } catch (error) {
            showErrorMessage('网络错误，请检查连接后重试');
            console.error('数据获取失败:', error);
        } finally {
            hideLoadingState();
            updateTimeDisplay();
        }
    }

    // 渲染所有数据
    function renderAllData(data) {
        // 渲染平台卡片
        renderPlatformCards(data);

        // 渲染平台图表
        renderPlatformChart(data);

        // 渲染话题列表
        renderTopicsList(data);
    }

    // 渲染平台卡片
    function renderPlatformCards(platformsData) {
        const container = document.getElementById('platformCards');
        container.innerHTML = '';

        // 获取平台列表并按热点数量排序
        const sortedPlatforms = Object.entries(platformsData)
                .sort((a, b) => b[1].count - a[1].count);

        sortedPlatforms.forEach(([platform, data]) => {
            const platformClass = `platform-${platform.toLowerCase().replace(/\s+/g, '')}`;
            const card = document.createElement('div');
            card.className = `bg-white rounded-xl p-5 card-shadow card-hover border-l-4 ${platformClass}`;
            card.innerHTML = `
          <div class="flex items-center justify-between mb-2">
            <h3 class="font-semibold">${platform}</h3>
            <span class="text-gray-400 text-sm">热点</span>
          </div>
          <p class="text-2xl font-bold">${data.count}</p>
          <div class="mt-2 text-xs text-gray-500">
            <i class="fa fa-clock-o mr-1"></i>
            <span>实时更新</span>
          </div>
        `;
            container.appendChild(card);
        });
    }

    // 渲染平台分布图表
    function renderPlatformChart(platformsData) {
        const ctx = document.getElementById('platformChart').getContext('2d');

        // 准备图表数据
        const labels = Object.keys(platformsData);
        const counts = Object.values(platformsData).map(data => data.count);
        const colors = labels.map(platform => {
            const className = `platform-${platform.toLowerCase().replace(/\s+/g, '')}`;
            const style = getComputedStyle(document.documentElement);
            return style.getPropertyValue(`--${className}`) || getRandomColor();
        });

        // 如果已有图表实例，先销毁
        if (chartInstance) {
            chartInstance.destroy();
        }

        // 创建新图表
        chartInstance = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: labels,
                datasets: [{
                    data: counts,
                    backgroundColor: colors,
                    borderWidth: 0,
                    hoverOffset: 10
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            boxWidth: 12,
                            padding: 15,
                            font: {
                                size: 11
                            }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function (context) {
                                const label = context.label || '';
                                const value = context.raw || 0;
                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                const percentage = Math.round((value / total) * 100);
                                return `${label}: ${value} (${percentage}%)`;
                            }
                        }
                    }
                },
                cutout: '70%',
                animation: {
                    animateScale: true,
                    animateRotate: true,
                    duration: 1000,
                    easing: 'easeOutQuart'
                }
            }
        });

        // 为颜色变量设置CSS变量，方便后续使用
        labels.forEach((platform, index) => {
            const className = `platform-${platform.toLowerCase().replace(/\s+/g, '')}`;
            document.documentElement.style.setProperty(`--${className}`, colors[index]);
        });
    }

    // 渲染话题列表
    function renderTopicsList(platformsData) {
        const container = document.getElementById('topicsContainer');
        container.innerHTML = '';

        // 获取平台列表并按热点数量排序
        const sortedPlatforms = Object.entries(platformsData)
                .sort((a, b) => b[1].count - a[1].count);

        sortedPlatforms.forEach(([platform, data]) => {
            const platformClass = `platform-${platform.toLowerCase().replace(/\s+/g, '')}`;

            // 创建平台话题区块
            const platformSection = document.createElement('div');
            platformSection.className = 'bg-white rounded-xl overflow-hidden card-shadow';

            // 平台标题栏
            const header = document.createElement('div');
            header.className = `px-6 py-4 border-b grid grid-cols-[1fr_auto_auto] gap-4 items-center`;
            header.innerHTML = `
              <div class="flex items-center">
                <div class="w-3 h-3 rounded-full mr-2 ${platformClass}"></div>
                <h3 class="font-bold text-lg">${platform}</h3>
                <span class="ml-4 text-sm text-gray-500">共 ${data.count} 个热点</span>
              </div>
              <div class="text-center text-sm font-semibold text-gray-500 w-24">热度值</div>
              <div class="text-right text-sm font-semibold text-gray-500 w-24">AI文章生成</div>
            `;
            platformSection.appendChild(header);

            // 话题列表
            const topicsList = document.createElement('div');
            topicsList.className = 'divide-y';

            // 只显示前5个话题，其余可通过展开查看
            const displayTopics = data.topics.slice(0, 5);
            const hasMore = data.topics.length > 5;

            displayTopics.forEach((topic) => {
                topicsList.appendChild(createTopicItem(topic, platform));
            });

            // 添加"查看更多"按钮
            if (hasMore) {
                const moreBtn = document.createElement('div');
                moreBtn.className = 'px-6 py-3 text-center text-primary hover:bg-gray-50 cursor-pointer transition-colors';
                moreBtn.innerHTML = `
            <span>查看全部 ${data.count} 个话题</span>
            <i class="fa fa-angle-down ml-1"></i>
          `;
                moreBtn.addEventListener('click', () => toggleAllTopics(moreBtn, data.topics, topicsList));
                topicsList.appendChild(moreBtn);
            }

            platformSection.appendChild(topicsList);
            container.appendChild(platformSection);
        });
    }

    // 创建单个话题项
    function createTopicItem(topic, platform) {
        const item = document.createElement('div');
        item.className = 'px-6 py-4 grid grid-cols-[1fr_auto_auto] gap-4 items-center hover:bg-gray-50 topic-item';

        item.innerHTML = `
        <div class="flex items-center">
          <span class="text-gray-400 w-5 mr-3">${topic.rank}</span>
          <div class="flex-1">
            <p class="line-clamp-1">${topic.title}</p>
            <div class="text-xs text-gray-500 mt-1 flex flex-wrap items-center gap-1">
              <span class="mr-1">关键词:</span>
              ${topic.keywords && topic.keywords.length > 0 ? topic.keywords.map(keyword => `<span style="display: inline-block; background-color: #DBEAFE; color: #1E40AF; font-size: 0.75rem; line-height: 1rem; padding: 0.125rem 0.625rem; border-radius: 9999px;">${keyword}</span>`).join('') : '无'}
              ${topic.time_info ? `<span class="ml-2" data-time-info="${topic.time_info}">时间: ${topic.time_info}</span>` : ''}
              ${topic.url ? `<a href="${topic.url}" target="_blank" class="text-blue-500 hover:underline ml-2">查看原文</a>` : ''}
            </div>
          </div>
        </div>
        <div class="flex items-center w-24 justify-center" data-test="hotness-section">
          <div class="flex items-center">
            <div class="w-16 bg-gray-200 rounded-full h-2.5 mr-2">
              <div class="bg-blue-600 h-2.5 rounded-full" style="width: ${Math.max(0, topic.hotness_score)}%"></div>
            </div>
            <span class="text-sm text-gray-500">${formatNumber(Math.max(0, topic.hotness_score))}</span>
          </div>
        </div>
        <div class="flex items-center w-24 justify-center">
          <button class="generate-article-btn bg-blue-500 hover:bg-blue-700 text-white font-bold py-1 px-2 rounded text-sm"
                  data-title="${topic.title}"
                  data-url="${topic.url || ''}"
                  data-platform="${platform}">
            生成内容
          </button>
        </div>
        `;

        // 添加事件监听器
        const generateBtn = item.querySelector('.generate-article-btn');
        if (generateBtn) {
            generateBtn.addEventListener('click', async () => {
                const title = generateBtn.dataset.title;
                const url = generateBtn.dataset.url;
                const platformName = generateBtn.dataset.platform;

                try {
                    const response = await fetch('/api/generate-article', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            title: title,
                            url: url,
                            platform: platformName
                        })
                    });
                    const result = await response.json();
                    if (result.success) {
                        alert('文章生成成功！');
                        console.log('生成文章结果:', result.data);
                    } else {
                        alert('文章生成失败: ' + (result.error || '未知错误'));
                    }
                } catch (error) {
                    console.error('生成文章请求出错:', error);
                    alert('生成文章请求出错，请检查网络或控制台。');
                }
            });
        }

        return item;
    }

    // 切换显示全部话题
    function toggleAllTopics(btn, allTopics, container) {
        // 检查当前是否已显示全部
        const isShowingAll = container.querySelectorAll('.topic-item').length === allTopics.length;

        if (isShowingAll) {
            // 只显示前5个
            container.innerHTML = '';
            allTopics.slice(0, 5).forEach((topic, index) => {
                container.appendChild(createTopicItem(topic, index + 1));
            });
            container.appendChild(btn);
            btn.innerHTML = `
          <span>查看全部 ${allTopics.length} 个话题</span>
          <i class="fa fa-angle-down ml-1"></i>
        `;
        } else {
            // 显示全部
            container.innerHTML = '';
            allTopics.forEach((topic, index) => {
                container.appendChild(createTopicItem(topic, index + 1));
            });
            container.appendChild(btn);
            btn.innerHTML = `
          <span>收起话题列表</span>
          <i class="fa fa-angle-up ml-1"></i>
        `;
        }
    }

    // 显示加载状态
    function showLoadingState() {
        const container = document.getElementById('topicsContainer');
        container.innerHTML = `
        <div class="flex justify-center items-center py-16">
          <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
        </div>
      `;

        // 刷新按钮添加旋转动画
        const refreshBtn = document.getElementById('refreshBtn').querySelector('i');
        refreshBtn.classList.add('animate-spin');
    }

    // 隐藏加载状态
    function hideLoadingState() {
        // 移除刷新按钮的旋转动画
        const refreshBtn = document.getElementById('refreshBtn').querySelector('i');
        refreshBtn.classList.remove('animate-spin');
    }

    // 显示成功消息
    function showSuccessMessage(message) {
        showStatusMessage(message, 'bg-green-50 text-green-600 border border-green-100');
    }

    // 显示错误消息
    function showErrorMessage(message) {
        showStatusMessage(message, 'bg-red-50 text-red-600 border border-red-100');
    }

    // 显示状态消息
    function showStatusMessage(message, className) {
        const container = document.getElementById('statusMessage');
        container.className = `mb-6 p-4 rounded-lg ${className} flex items-center`;
        container.innerHTML = `
        <i class="fa ${className.includes('green') ? 'fa-check-circle' : 'fa-exclamation-circle'} mr-2"></i>
        <span>${message}</span>
      `;
        container.classList.remove('hidden');

        // 3秒后自动隐藏
        setTimeout(() => {
            container.classList.add('hidden');
        }, 3000);
    }

    // 更新时间显示
    function updateTimeDisplay() {
        const now = new Date();
        const timeStr = now.toLocaleTimeString();
        const dateStr = now.toLocaleDateString();
        document.getElementById('updateTime').textContent = `最后更新: ${dateStr} ${timeStr}`;
    }

    // 切换主题
    function toggleTheme() {
        isDarkMode = !isDarkMode;
        const themeIcon = document.getElementById('themeToggle').querySelector('i');

        if (isDarkMode) {
            document.documentElement.classList.add('dark');
            themeIcon.classList.remove('fa-moon-o');
            themeIcon.classList.add('fa-sun-o');
            document.body.classList.add('bg-gray-900', 'text-white');
            document.body.classList.remove('bg-gray-50', 'text-dark');
        } else {
            document.documentElement.classList.remove('dark');
            themeIcon.classList.remove('fa-sun-o');
            themeIcon.classList.add('fa-moon-o');
            document.body.classList.remove('bg-gray-900', 'text-white');
            document.body.classList.add('bg-gray-50', 'text-dark');
        }
    }

    // 格式化数字（添加千位分隔符）
    function formatNumber(num) {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    // 生成随机颜色（用于图表）
    function getRandomColor() {
        const letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
</script>
<script>
    function clearHotTopicsCacheAndNavigate() {
        sessionStorage.removeItem('cachedHotTopics');
        window.location.href = '/';
    }
</script>
</body>
</html>